iT邦幫忙

2024 iThome 鐵人賽

DAY 3
2
自我挑戰組

每日挑戰:從零開始的 Python 學習之旅系列 第 3

【Day 3】以Poetry管理工具來建立虛擬環境

  • 分享至 

  • xImage
  •  

Hi 大家好,

今天要介紹的內容是如何安裝Poetry管理工具,並且使用Poetry的功能來建立虛擬環境和相關套件。

Q: 為什麼要建立虛擬環境?
A: 在使用Python程式語言開發相關項目時候,虛擬環境可以說是非常重要的一環。
 原因是:
  * 虛擬環境就是一種完全獨立的開發環境
  * 依賴隔離:隔離了不同專案開發時候套件的相互依賴性和影響的關係
  * 簡化部屬:確保在開發環境中安裝和測試的所有依賴都能被正確記錄,在部屬時可以精準重現
  * 提高安全性:使用虛擬環境可以避免意外修改系統的全局 Python 環境

接下來我們就來實作如何安裝的步驟:
※ 我所示範的步驟,是自己嘗試安裝過的過程,但也只是其中一種方法提供參考,請斟酌服用

  1. 安裝Poetry

    > Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
    > Invoke-RestMethod -Uri https://get.scoop.sh | Invoke-Expression
    

    https://ithelp.ithome.com.tw/upload/images/20240803/20165522WH8GDwyGT2.png

    • 安裝 pipx 工具
    scoop install pipx
    

    https://ithelp.ithome.com.tw/upload/images/20240803/20165522QBbPtURuEe.png

    • 安裝 poetry
      以系統管理員身分執行PowerShell 7
    pipx install poetry
    
    PS D:\Project\5xcampus\Python\20240725_python_demo> pipx install poetry
     ⚠️  File exists at C:\Users\Eric\.local\bin\poetry.exe and points to 
     C:\Users\Eric\.local\bin\poetry.exe, not
     C:\Users\Eric\pipx\venvs\poetry\Scripts\poetry.exe. Not modifying.
       installed package poetry 1.8.3, installed using Python 3.12.4
       These apps are now globally available
         - poetry.exe (symlink missing or pointing to unexpected location)
     done! ✨ 🌟 ✨
     PS D:\Project\5xcampus\Python\20240725_python_demo>
    

    查看目前安裝版本

    PS D:\Project\5xcampus\Python\20240725_python_demo> poetry --version
    Poetry (version 1.8.3)
    PS D:\Project\5xcampus\Python\20240725_python_demo>
    
  2. 使用Poetry confing 查看設定檔案

    PS D:\Project\5xcampus\Python\practice> poetry config --list
    cache-dir = "C:\\Users\\Eric\\AppData\\Local\\pypoetry\\Cache"
    experimental.system-git-client = false
    installer.max-workers = null
    installer.modern-installation = true
    installer.no-binary = null
    installer.parallel = true
    keyring.enabled = true
    solver.lazy-wheel = true
    virtualenvs.create = true
    virtualenvs.in-project = false
    virtualenvs.options.always-copy = false
    virtualenvs.options.no-pip = false
    virtualenvs.options.no-setuptools = false
    virtualenvs.options.system-site-packages = false
    virtualenvs.path = "{cache-dir}\\virtualenvs"  #  C:\Users\Eric\AppData\Local\pypoetry\Cache\virtualenvs
    virtualenvs.prefer-active-python = false
    virtualenvs.prompt = "{project_name}-py{python_version}"
    warnings.export = true
    PS D:\Project\5xcampus\Python\practice>
    

    其中的環境設定檔案中的 virtualenvs.in-project 預設會是 null 或是 false
    這行配置選項表示: 要不要在Poetry啟動一個新的shell的時候自動建立虛擬環境

    flase: 之後可以自己手動建立 poetry new .venv
    true: 啟動shell時候自動建立
    這裡我們先把配置改為true

    PS D:\Project\5xcampus\Python\practice> poetry config virtualenvs.in-project true
    PS D:\Project\5xcampus\Python\practice> poetry config --list
    cache-dir = "C:\\Users\\Eric\\AppData\\Local\\pypoetry\\Cache"
    experimental.system-git-client = false
    installer.max-workers = null
    installer.modern-installation = true
    installer.no-binary = null
    installer.parallel = true
    keyring.enabled = true
    solver.lazy-wheel = true
    virtualenvs.create = true
    virtualenvs.in-project = true
    virtualenvs.options.always-copy = false
    virtualenvs.options.no-pip = false
    virtualenvs.options.no-setuptools = false
    virtualenvs.options.system-site-packages = false
    virtualenvs.path = "{cache-dir}\\virtualenvs"  # C:\Users\Eric\AppData\Local\pypoetry\Cache\virtualenvs
    virtualenvs.prefer-active-python = false
    virtualenvs.prompt = "{project_name}-py{python_version}"
    warnings.export = true
    PS D:\Project\5xcampus\Python\practice>
    
  3. 建立一新資料夾practice,並且進入資料夾

  4. 在當前目錄下建立一個 pyproject.toml 文件來管理項目的依賴和配置

    poetry init => 會有互動式問答,詢問一些關於項目的基本信息,可自行定義
    
    PS D:\Project\5xcampus\Python\practice> poetry init
    A pyproject.toml file with a poetry section already exists.
    PS D:\Project\5xcampus\Python\practice> poetry init
    
    This command will guide you through creating your pyproject.toml config.
    
    Package name [practice]:
    Version [0.1.0]:
    Description []:
    Author [erichsu <filafila0521@gmail.com>, n to skip]:
    License []:
    Compatible Python versions [^3.12]:
    
    Would you like to define your main dependencies interactively? (yes/no) [yes]
    You can specify a package in the following forms:
      - A single name (requests): this will search for matches on PyPI
      - A name and a constraint (requests@^2.23.0)
      - A git url (git+https://github.com/python-poetry/poetry.git)
      - A git url with a revision (git+https://github.com/python-poetry/poetry.git#develop)
      - A file path (../my-package/my-package.whl)
      - A directory (../my-package/)
      - A url (https://example.com/packages/my-package-0.1.0.tar.gz)
    
    Package to add or search for (leave blank to skip):
    
    Would you like to define your development dependencies interactively? (yes/no) [yes]
    Package to add or search for (leave blank to skip):
    
    Generated file
    
    [tool.poetry]
    name = "practice"
    version = "0.1.0"
    description = ""
    authors = ["erichsu <filafila0521@gmail.com>"]
    readme = "README.md"
    
    [tool.poetry.dependencies]
    python = "^3.12"
    
    
    [build-system]
    requires = ["poetry-core"]
    build-backend = "poetry.core.masonry.api"
    
    
    Do you confirm generation? (yes/no) [yes]
    PS D:\Project\5xcampus\Python\practice>
    
    poetry init -n => 會省略互動式問答,基本訊息都採用預設方式 
    
    PS D:\Project\5xcampus\Python\practice> poetry init -n
    PS D:\Project\5xcampus\Python\practice>
    

    查看pyproject.toml內容

    PS D:\Project\5xcampus\Python\practice> cat .\pyproject.toml
    [tool.poetry]
    name = "practice"
    version = "0.1.0"
    description = ""
    authors = ["xxx <xxx@gmail.com>"]
    readme = "README.md"
    
    [tool.poetry.dependencies]
    python = "^3.12"
    
    
    [build-system]
    requires = ["poetry-core"]
    build-backend = "poetry.core.masonry.api"
    PS D:\Project\5xcampus\Python\practice>
    
  5. 使用Poetry shell啟動一新的虛擬環境

    PS D:\Project\5xcampus\Python\practice> poetry shell
    Creating virtualenv practice in D:\Project\5xcampus\Python\practice\.venv
    Spawning shell within D:\Project\5xcampus\Python\practice\.venv
    PowerShell 7.4.3
    
       A new PowerShell stable release is available: v7.4.4
       Upgrade now, or check out the release page at:
         https://aka.ms/PowerShell-Release?tag=v7.4.4
    
    (practice-py3.12) PS D:\Project\5xcampus\Python\practice> ls
    
        Directory: D:\Project\5xcampus\Python\practice
    
    Mode                 LastWriteTime         Length Name
    ----                 -------------         ------ ----
    d----          2024/8/3 下午 02:55                .venv
    -a---          2024/8/3 下午 02:52            280 pyproject.toml
    
    (practice-py3.12) PS D:\Project\5xcampus\Python\practice>
    

    其中(practice-py3.12)字樣表示已經進入到虛擬環境中

  6. 使用poetry add <套件名稱>,來安裝相關套件

    (practice-py3.12) PS D:\Project\5xcampus\Python\practice> poetry add django
    Using version ^5.0.7 for django
    
    Updating dependencies
    Resolving dependencies... (0.2s)
    
    Package operations: 4 installs, 0 updates, 0 removals
    
      - Installing asgiref (3.8.1)
      - Installing sqlparse (0.5.1)
      - Installing tzdata (2024.1)
      - Installing django (5.0.7)
    
    Writing lock file
    (practice-py3.12) PS D:\Project\5xcampus\Python\practice>
    
  7. 使用poetry show查看是否安裝成功

    (practice-py3.12) PS D:\Project\5xcampus\Python\practice> poetry show
    Error: poetry.lock not found. Run `poetry lock` to create it.
    (practice-py3.12) PS D:\Project\5xcampus\Python\practice> poetry lock
    Updating dependencies
    Resolving dependencies... (0.1s)
    
    Writing lock file
    (practice-py3.12) PS D:\Project\5xcampus\Python\practice> poetry show
    asgiref  3.8.1  ASGI specs, helper code, and adapters
    django   5.0.7  A high-level Python web framework that encourages rapid development and clean, pragmatic design.
    sqlparse 0.5.1  A non-validating SQL parser.
    tzdata   2024.1 Provider of IANA time zone data
    (practice-py3.12) PS D:\Project\5xcampus\Python\practice>
    
  8. 如何退出虛擬環境 ( exitCtrl+D )

    (practice-py3.12) PS D:\Project\5xcampus\Python\practice> exit
    PS D:\Project\5xcampus\Python\practice>
    

以上就是今天要介紹的內容,我們明天見~


上一篇
【Day 2】常用開發工具和套件 - pyenv
下一篇
【Day 4】基礎語法 - 變數篇
系列文
每日挑戰:從零開始的 Python 學習之旅30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言